<template>
  <div class="theme-container" ref="container">
    <el-button class="toggle-theme" @click="toggleTheme">
        <el-icon v-if="isDark" class="mode-icon" name="sunny"><Sunny/></el-icon>
        <el-icon v-else class="mode-icon" name="moon"><Moon/></el-icon>
    </el-button>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useDark, useToggle } from '@vueuse/core'
import {Sunny, Moon} from '@element-plus/icons-vue'

const isDark = useDark()

// 使用 useToggle 函数来切换暗黑模式
const toggleDark = useToggle(isDark)

// 获取容器引用
const container = ref(null)

// 主题切换函数
const toggleTheme = (event) => {
  // 获取点击位置坐标
  const x = event.clientX
  const y = event.clientY

  // 计算结束半径（从点击位置到屏幕最远点的距离）
  const endRadius = Math.hypot(
      Math.max(x, innerWidth - x),
      Math.max(y, innerHeight - y)
  )

  // 兼容性处理：如果浏览器不支持 View Transitions API，则直接切换主题
  if (!document.startViewTransition) {
    toggleDark()
    return
  }

  // 使用 View Transitions API 创建过渡效果
  const transition = document.startViewTransition(async () => {
    toggleDark()
  })

  // 过渡准备就绪后，执行动画
  transition.ready.then(() => {
    // 定义圆形裁剪路径
    const clipPath = [
      `circle(0px at ${x}px ${y}px)`,
      `circle(${endRadius}px at ${x}px ${y}px)`,
    ]

    // 根据当前主题状态决定动画方向
    document.documentElement.animate(
        {
          clipPath: isDark.value ? [...clipPath].reverse() : clipPath,
        },
        {
          duration: 400,
          easing: "ease-in",
          pseudoElement: isDark.value
              ? "::view-transition-old(root)"
              : "::view-transition-new(root)",
        }
    )
  })
}
</script>

<style lang="scss">
.theme-container {
  position: relative;
  overflow: hidden;
}

.toggle-theme {
  position: fixed;
  bottom: 50px;
  right: 20px;
  width: 50px;
  height: 50px;
  border-radius: 50%;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
  z-index: 100;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: rgba(255, 255, 255, 0.4);
  border: none;
  cursor: pointer;
  transition: all 0.3s ease;

  .dark & {
    background-color: rgba(30, 30, 30, 0.9);
  }

  &:hover {
    transform: scale(1.1);
  }
}

.mode-icon {
  font-size: 24px;
  color: var(--el-color-primary);

  .dark & {
    color: var(--el-color-warning);
  }
}

</style>